package net.qhzw.vip.qiyu.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;

import java.util.HashMap;
import java.util.Map;

/**
 * 自动收货
 */
@SpringBootConfiguration
public class ReceiptTtlQueueConfig {

    //普通交换机的名称
    public final static String RECEIPT_EXCHANGE = "RECEIPT_EXCHANGE";
    //死信交换机的名称
    public final static String RECEIPT_DEAD_LETTER_EXCHANGE = "RECEIPT_DEAD_LETTER_EXCHANGE";
    //普通队列的名称
    public final static String QUEUE_RECEIPT = "QUEUE_RECEIPT";
    //死信队列的名称
    public final static String DEAD_LETTER_QUEUE_RECEIPT = "DEAD_LETTER_QUEUE_RECEIPT";

    //声明交换机 cancelOrderExchange
    @Bean("receiptExchange")
    public DirectExchange receiptExchange(){
        return new DirectExchange(RECEIPT_EXCHANGE);
    }
    //声明交换机 cancelOrderDeadLetterExchange
    @Bean("receiptDeadLetterExchange")
    public DirectExchange receiptDeadLetterExchange(){
        return new DirectExchange(RECEIPT_DEAD_LETTER_EXCHANGE);
    }

    //声明普通队列 TTL
    @Bean("queueReceipt")
    public Queue queueReceipt(){
        //正常队列绑定死信交换机信息，因为正常队列消息会变为死信
        Map<String, Object> arguments = new HashMap<>();
        //正常队列设置死信交换机 参数 key 是固定值
        arguments.put("x-dead-letter-exchange",RECEIPT_DEAD_LETTER_EXCHANGE);
        //正常队列设置死信 routing-key 参数 key 是固定值
        arguments.put("x-dead-letter-routing-key", "RECEIPT");
        //设置过期时间 10s,单位是ms，可以在消费者正常队列处设置，也可以在生产者发送处设置
        arguments.put("x-message-ttl", 1000 * 60 * 60 * 24 * 14);
        return QueueBuilder.durable(QUEUE_RECEIPT).withArguments(arguments).build();
    }

    //声明死信队列
    @Bean("deadLetterQueueReceipt")
    public Queue deadLetterQueueReceipt(){
        //没有参数
        return QueueBuilder.durable(DEAD_LETTER_QUEUE_RECEIPT).build();
    }

    //五大组件完毕，开始互相绑定
    @Bean
    public Binding queueReceiptBindingReceiptExchange(@Qualifier("queueReceipt") Queue queueReceipt,
                                  @Qualifier("receiptExchange") DirectExchange receiptExchange){
        //将 X 正常交换机和 QA 队列 绑定
        return BindingBuilder.bind(queueReceipt).to(receiptExchange).with("receipt");
    }

    @Bean
    public Binding deadLetterQueueReceiptBindingReceiptDeadLetterExchange(@Qualifier("deadLetterQueueReceipt") Queue deadLetterQueueReceipt,
                                  @Qualifier("receiptDeadLetterExchange") DirectExchange receiptDeadLetterExchange){
        //将 Y 死信交换机和 QD 死信队列 绑定
        return BindingBuilder.bind(deadLetterQueueReceipt).to(receiptDeadLetterExchange).with("RECEIPT");
    }

}
